- Instance Initializer block
- Example without initializer block-
- Output-
- How initializer block works with constructor
- In the below example, we have created a constructor and the initializer block. We will get to know which will execute when.
- Output-
- Instance initializer block rules-
- Instance initializer block invoked after super()
- Example-
- Output-
Instance Initializer block
This block will allow you to initialize the data member instance. This block will get executed every time the class object is created. You can initialize the instance variable directly but some extra steps will be required to initialize the instance variable within the instance initializer block.
Example without initializer block-
Example with Initializer block-
Output-
The initializer block is used when we have to person some action while assigning value to the instance data member.
In Java, these operations can be performed within the method, constructor and block.
How initializer block works with constructor
In the below example, we have created a constructor and the initializer block. We will get to know which will execute when.
Example-
Output-
It seems that the initializer block is executed first but this is not the case, the compiler will copy the initializer block in the constructor. Thus the compiler will get invoked first with the object creation.
Instance initializer block rules-
- The block is created with object creation.
- This block will get invoked after the parent’s class constructor.
- This block will get executed in the order where they appear.
Instance initializer block invoked after super()
Example-
Output-